package autoTest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;

import autoTest.command.Params;
import autoTest.utils.TextUtils;
import net.sf.json.JSONObject;

public class ConfigurationReader {
	public static Configuration readConfiguration() throws IOException {
		File directory = new File("");//参数为空 
		String courseFile = directory.getCanonicalPath() ; 
		String path = new String(courseFile + "\\conf\\config.json");
		File file = new File(path);
		BufferedReader br = new BufferedReader(new FileReader(file));
		String fileContent = new String();		//局部变量，执行完函数内容被清理
		String tmpStr;
		while((tmpStr = br.readLine()) != null) {
			fileContent = fileContent + tmpStr;
		}
		br.close();
		
		Configuration conf = new Configuration();
		JSONObject jo = JSONObject.fromObject(fileContent);
		if (jo.has(Params.CON_PORT)) {
			conf.setPort(jo.getString(Params.CON_PORT));
		}
		if (jo.has(Params.CON_ROOT)) {
			conf.setRoot(jo.getString(Params.CON_ROOT));
		}
		if (jo.has(Params.CON_GET_TASK_RESULT_TASK)) {
			conf.setGetTaskResultUrl(jo.getString(Params.CON_GET_TASK_RESULT_TASK));
		}
		if (jo.has(Params.CON_GET_TASK_URL)) {
			conf.setGetTaskUrl(jo.getString(Params.CON_GET_TASK_URL));
		}
		if (jo.has(Params.CON_QUERRY_DEVICE_URL)) {
			conf.setQuerryDeviceUrl(jo.getString(Params.CON_QUERRY_DEVICE_URL));
		}
		if (jo.has(Params.CON_REPORT_STATUS_URL)) {
			conf.setReportStatusUrl(jo.getString(Params.CON_REPORT_STATUS_URL));
		}
		if (jo.has(Params.CON_REPORT_URL)) {
			conf.setReportUrl(jo.getString(Params.CON_REPORT_URL));
		}
		if (jo.has(Params.CON_START_REMOT_URL)) {
			conf.setStartRemoteUrl(jo.getString(Params.CON_START_REMOT_URL));
		}
		if (jo.has(Params.CON_START_URL)) {
			conf.setStartUrl(jo.getString(Params.CON_START_URL));
		}
		if (jo.has(Params.CON_STOP_URL)) {
			conf.setStopUrl(jo.getString(Params.CON_STOP_URL));
		}
		if (jo.has(Params.SET_BLACKLIST_URL)) {
			conf.setSetBlacklistUrl(jo.getString(Params.SET_BLACKLIST_URL));
		}
		if (jo.has(Params.QUERRY_BLACKLIST_URL)) {
			conf.setQuerryBlacklistUrl(jo.getString(Params.QUERRY_BLACKLIST_URL));
		}
		conf.setIp(getLocalIp());
		return conf;
	}
	
	private static String getLocalIp() {
        InetAddress ia = null;
        String localIp = new String("");
        try {
            ia = ia.getLocalHost();
            localIp = ia.getHostAddress();
            System.out.println("本机的ip是 ：" + localIp);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        
        if (!TextUtils.isEmpty(localIp)) {
        	return localIp;
        } else {
        	return null;
        }
	}
}
